﻿using BillHelper;
using DemoForBillOcr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaxAssistantBase;

namespace ShiBieProject
{
    public class InvoiceOcrCompanyNameTool
    {
        private static WsdLogger ocrlog = new WsdLogger("OcrLog");
        public static string getCompanyName(List<InvoiiceOcrModel> idIOMList, List<InvoiceSonModel> idIOMSonList)
        {
            string companyName, taxNo;

            getCompanyName(idIOMList, idIOMSonList, out companyName, out taxNo);

            return companyName;
        }
        /// <summary>
        /// 1.得到公司名
        /// </summary>
        /// <param name="idIOMList"></param>
        /// <param name="idIOMSonList"></param>
        /// <param name="name"></param>
        public static string getCompanyName(List<InvoiiceOcrModel> idIOMList, List<InvoiceSonModel> idIOMSonList, out string companyName, out string taxNo)
        {
            companyName = "";
            taxNo = "";
            foreach (InvoiiceOcrModel im in idIOMList) {
                if (im.companyState=="1") {
                    if (im.invoiceOcrSonLists!=null) {
                        if (im.invoiceOcrSonLists.Count>0) {
                            if (im.invoiceOcrSonLists[0].isProviderOrCustomer == "1") {
                                //购方为主公司
                            } else if (im.invoiceOcrSonLists[0].isProviderOrCustomer == "0") {
                                //销方为主公司
                            }
                        }
                    }
                }
            }
            //1.得到orc 公司名称和税号，即最多orc名称
            if (idIOMList == null || idIOMList.Count == 0)
            {
                return CompanyOrMoneyStateEnum.NotMatch;
            }

            if (idIOMList.Count == 1)
            {
                if(idIOMList[0].invoiceOcrSonLists != null)
                {
                    if (idIOMList[0].invoiceOcrSonLists.Count>0) {
                        string state;

                        var ocrSon = idIOMList[0].invoiceOcrSonLists[0];
                        chulisuanfaOne(ocrSon.gfcompanyname, ocrSon.gftaxnumber, ocrSon.xfcompanyname, ocrSon.xftaxnumber, out companyName, out taxNo, out state);
                        return state;
                    }
                }
            }
            else if (idIOMList.Count > 1)
            {
                string ocrCompanyName, ocrTaxNo;
                biduiresult(idIOMSonList, out ocrCompanyName, out ocrTaxNo);
                if ((!string.IsNullOrEmpty(ocrCompanyName)) && (!string.IsNullOrEmpty(ocrTaxNo)))
                {
                    string state;
                    chulisuanfa(ocrCompanyName, ocrTaxNo, out companyName, out taxNo, out state);

                    return state;
                }
            }

            return CompanyOrMoneyStateEnum.NotMatch;
        }

       
        //给公司赋值
        public static List<InvoiiceOcrModel> fuzhiCompany(List<InvoiiceOcrModel> idIOMList, string companyname, string comptaxnum,string companyState)
        {
            for (int j = 0; j < idIOMList.Count; j++)
            {
                idIOMList[j].companyName = companyname;
                idIOMList[j].companyTaxnum = comptaxnum;
                idIOMList[j].companyState = companyState;
            }
            return idIOMList;
        }

        private static void biduiresult(List<InvoiceSonModel> biduilist, out string companyname, out string comptaxnum)
        {
            comptaxnum = "";
            companyname = "";

            List<string> list = new List<string>();
            InvoiceSonModel ism = new InvoiceSonModel();
            int linshigf = 0;
            int errornum = 0;
            string gfmax = "";
            try
            {
                if (biduilist != null)
                {
                    if (biduilist.Count > 0)
                    {
                        try
                        {
                            gfmax = Convert.ToString(biduilist.Max(work => int.Parse(work.gfbankAccount == null ? "0" : work.gfbankAccount)));
                        }
                        catch (Exception ex)
                        {
                            WsdLogger.yxlog("error", "比对转化错误" + ex.Message);
                        }
                        for (int i = 0; i < biduilist.Count; i++)
                        {
                            errornum++;
                            try
                            {
                                if (gfmax != "" && gfmax != null)
                                {
                                    if (gfmax == biduilist[i].gfbankAccount)
                                    {
                                        linshigf = int.Parse(biduilist[i].gfbankAccount);
                                        if (HongFengCompanyOrVendorsTool.companyAll != null)
                                        {
                                            var lists = from complist in HongFengCompanyOrVendorsTool.companyAll where complist.companyTaxnum == biduilist[i].gftaxnumber select complist;
                                            var lists2 = from complist in HongFengCompanyOrVendorsTool.companyAll where complist.companyName == biduilist[i].gfcompanyname select complist;
                                            if (lists.ToList().Count > 0)
                                            {
                                                ism.gfcompanyname = lists.ToList()[0].companyName;
                                                ism.gftaxnumber = biduilist[i].gftaxnumber;
                                                break;
                                            }
                                            else if (lists2.ToList().Count > 0)
                                            {
                                                ism.gfcompanyname = biduilist[i].gfcompanyname;
                                                ism.gftaxnumber = lists2.ToList()[0].companyTaxnum;
                                                break;
                                            }
                                            else
                                            {
                                                if (biduilist[i].gfcompanyname.Contains("上海"))
                                                {
                                                    ism.gfcompanyname = biduilist[i].gfcompanyname;
                                                    ism.gftaxnumber = biduilist[i].gftaxnumber;
                                                    continue;
                                                }
                                                else
                                                {
                                                    ism.gfcompanyname = biduilist[i].gfcompanyname;
                                                    ism.gftaxnumber = biduilist[i].gftaxnumber;
                                                }

                                            }
                                        }
                                        else
                                        {
                                            ism.gfcompanyname = biduilist[i].gfcompanyname;
                                            ism.gftaxnumber = biduilist[i].gftaxnumber;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                WsdLogger.yxlog("error", "第" + errornum + "条数据比对得出公司" + ex.Message);
                                continue;
                            }           
                        }
                        comptaxnum = ism.gftaxnumber;
                        companyname = ism.gfcompanyname;
                    }
                }
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "数据比对得出公司：" + ex.Message);
            }

            //}
        }

        public static bool chulisuanfa(string orcCompanyName, string orcTaxNo, out string companyName, out string taxNo, out string companyState)
        {
            return chulisuanfaOne(orcCompanyName, orcTaxNo, string.Empty, string.Empty, out companyName, out taxNo, out companyState);
        }

        public static bool chulisuanfaOne(string gfOrcCompanyName, string gfOrcTaxNo, string xfOrcCompanyName, string xfOrcTaxNo, out string companyName, out string taxNo, out string companyState)
        {
            List<BatchInfo> company = new List<BatchInfo>();
            //购方匹配
            if (!string.IsNullOrEmpty(gfOrcTaxNo))
            {
                var gflist = from gf in HongFengCompanyOrVendorsTool.companyAll where gf.companyTaxnum == gfOrcTaxNo select gf;
                company = gflist.ToList();
                if (company!=null) {
                    if (company.Count > 0)
                    {
                        companyName = company[0].companyName;
                        taxNo = company[0].companyTaxnum;

                        //按公司税号完全匹配
                        companyState = CompanyOrMoneyStateEnum.CompanyTaxNumberPerfectMatch;

                        return true;
                    }
                }
            }

            if (!string.IsNullOrEmpty(gfOrcCompanyName))
            {
                var gflist = from gf in HongFengCompanyOrVendorsTool.companyAll where gf.companyName == gfOrcCompanyName select gf;
                company = gflist.ToList();
                if (company!=null) {
                    if (company.Count > 0)
                    {
                        companyName = company[0].companyName;
                        taxNo = company[0].companyTaxnum;
                        //按公司税号完全匹配
                        companyState = CompanyOrMoneyStateEnum.CompanyNamePerfectMatch;
                        return true;
                    }
                }
            }

            //销方
            if (!string.IsNullOrEmpty(xfOrcTaxNo))
            {
                var gflist = from gf in HongFengCompanyOrVendorsTool.companyAll where gf.companyTaxnum == xfOrcTaxNo select gf;
                company = gflist.ToList();
                if (company!=null) {
                    if (company.Count > 0)
                    {
                        companyName = company[0].companyName;
                        taxNo = company[0].companyTaxnum;

                        //按公司税号完全匹配
                        companyState = CompanyOrMoneyStateEnum.CompanyTaxNumberPerfectMatch;

                        return true;
                    }
                }
            }

            if (!string.IsNullOrEmpty(xfOrcCompanyName))
            {
                var gflist = from gf in HongFengCompanyOrVendorsTool.companyAll where gf.companyName == xfOrcCompanyName select gf;
                company = gflist.ToList();
                if (company!=null) {
                    if (company.Count > 0)
                    {
                        companyName = company[0].companyName;
                        taxNo = company[0].companyTaxnum;

                        //按公司税号完全匹配
                        companyState = CompanyOrMoneyStateEnum.CompanyNamePerfectMatch;

                        return true;
                    }
                }
            }

            if(IsNotEmpty(gfOrcCompanyName, gfOrcTaxNo))
            {
                //购方 模糊匹配
                CompanyShaiXuan(gfOrcCompanyName, gfOrcTaxNo, out companyName, out taxNo, out companyState);
                if ((!string.IsNullOrEmpty(companyName)) && (!string.IsNullOrEmpty(taxNo)))
                {
                    return true;
                }
            }

            if (IsNotEmpty(xfOrcCompanyName, xfOrcTaxNo))
            {
                //销方 模糊匹配
                return CompanyShaiXuan(xfOrcCompanyName, xfOrcTaxNo, out companyName, out taxNo, out companyState);
            }

            companyName = gfOrcCompanyName;
           taxNo = gfOrcTaxNo;
            companyState = CompanyOrMoneyStateEnum.NotMatch;
            return false;
        }

        private static bool IsNotEmpty(string companyName,string taxNo)
        {
            return (!string.IsNullOrEmpty(companyName)) && (!string.IsNullOrEmpty(taxNo));
        }

        private static bool CompanyShaiXuan(string orcCompanyName, string orcTaxNo, out string companyName, out string taxNo, out string companyState)
        {
            int xiangsidu = 0;
            int xiangsidubidui = 0;
            int tiaoNim = 0;
            string companymingzi = "";
            string companyshuihao = "";
            companyName = taxNo = string.Empty;

            //1.1判断相似的数据是否存在并计数
            //1.2如果存在则计数后再执行下一个识别号在计数
            //1.3与上一个计数比较if大就替代上一个if小就保留上一个
            //2.1比较完成后得出最多相似度和相应公司税号用相似度和识
            //别的税号比较如果大于位数减三则判定为该公司否则新建识别公司手动修改或不修改
            foreach (var item in HongFengCompanyOrVendorsTool.companyAll)
            {
                tiaoNim++;
                try {
                    if (item.companyTaxnum.Length == orcTaxNo.Length)
                    {
                        xiangsidu = InvoiceOcrTool.getTaxNum(orcTaxNo, item.companyTaxnum);//获取税号相似度
                        if (xiangsidubidui > 0)
                        {
                            if (xiangsidubidui < xiangsidu)
                            {
                                companymingzi = item.companyName;
                                companyshuihao = item.companyTaxnum;
                                xiangsidubidui = xiangsidu;
                            }
                            else if (xiangsidubidui > xiangsidu)
                            {
                                //全都保留
                            }
                        }
                        else
                        {
                            companymingzi = item.companyName;
                            companyshuihao = item.companyTaxnum;
                        }
                    }
                    if (xiangsidubidui == 0)
                    {
                        xiangsidubidui = xiangsidu;
                    }
                    xiangsidu = 0;
                }
                catch (Exception ex) {
                    WsdLogger.yxlog("error", "第" + tiaoNim+ "条比对税号错误" + ex.Message);
                    continue;
                }
             
            }
            if (xiangsidubidui > ((orcTaxNo.Length - 2) > 0 ? (orcTaxNo.Length - 2) : 1000))
            {
                taxNo = companyshuihao;
                companyName = companymingzi;

                companyState = CompanyOrMoneyStateEnum.CompanyTaxNumberPartialMatch;
                return true;
            }
            int tempjs = 0;
            string maxName = "";
            string maxTaxNo = "";
            int duibiNum = 0;
            //进行公司名称对比
            foreach (var item in HongFengCompanyOrVendorsTool.companyAll)
            {
                duibiNum++;
                try {
                    int fengzhi = 0;
                    int iss = InvoiceOcrTool.NameXianSiD(orcCompanyName, item.companyName.Replace("公司", ""));
                    string comnames = (orcCompanyName.Replace("公司", "")).Replace("有限", "");
                    if (comnames.Length >= 6 && comnames.Length < 8)
                    {
                        fengzhi = 5;
                    }
                    else if (comnames.Length >= 8)
                    {
                        fengzhi = 7;
                    }
                    else if (comnames.Length < 6)
                    {
                        fengzhi = 3;
                    }
                    if (iss >= fengzhi)
                    {
                        if (tempjs != 0)
                        {
                            if (tempjs > iss)
                            {
                                //保留
                            }
                            else
                            {
                                tempjs = iss;
                                maxTaxNo = item.companyTaxnum;
                                maxName = item.companyName;
                            }
                        }
                        else
                        {
                            tempjs = iss;
                            maxTaxNo = item.companyTaxnum;
                            maxName = item.companyName;
                        }
                    }
                } catch (Exception ex) {
                    WsdLogger.yxlog("error", "第" + tiaoNim + "进行公司名称对比" + ex.Message);
                    continue;
                }
              
            }

            if ((!string.IsNullOrEmpty(maxTaxNo)) && (!string.IsNullOrEmpty(companyName)))
            {
                taxNo = maxTaxNo;
                companyName = maxName;
                companyState = CompanyOrMoneyStateEnum.CompanyNamePartialMatch;

                return true;
            }

            companyState = CompanyOrMoneyStateEnum.NotMatch;
      
            if ((!string.IsNullOrEmpty(orcCompanyName))&&(!string.IsNullOrEmpty(orcTaxNo))) {
                companyName = orcCompanyName;
                taxNo = orcTaxNo;
                NewCompany(orcCompanyName, orcTaxNo);
            }
            return false;
        }

    
        //新建公司
        private static void NewCompany(string companyname, string comptaxnum)
        {
            string apiurl2 = ApiUrlList.SAVECOMPANY;
            invoiceCompany icp = new invoiceCompany();
            icp.companyName = companyname;
            icp.taxNo = comptaxnum;
            icp.ocrCompanyName = companyname;
            icp.ocrTaxNo = comptaxnum;
            newCompany(icp, apiurl2);
        }

        //新建公司
        private static void newCompany(invoiceCompany icp, string apiurl2)
        {
            string tpresult = "";
            try
            {
                ocrlog.Write("新建公司名称：" + icp.companyName + "新建公司税号：" + icp.taxNo);
                //存入新公司，如果表里有要返回公司数据
                var result = RestOrcTool.Post(out tpresult, icp, apiurl2);
                ocrlog.Write("新建公司成功");
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "新建公司错误" + ex.Message);
                return;
            }
        }

    }
}
